package com.chilly.stream;

import java.util.*;
import java.util.stream.Stream;

/**
 * Created by Chilly Cui on 2020/11/19.
 */
public class StreamDemo {
    public static void main(String[] args) {
        List<String> stringCollection = new ArrayList<>();
        stringCollection.add("ddd2");
        stringCollection.add("aaa2");
        stringCollection.add("bbb1");
        stringCollection.add("aaa1");
        stringCollection.add("bbb3");
        stringCollection.add("ccc");
        stringCollection.add("bbb2");
        stringCollection.add("ddd1");

        /*
        // 测试 Filter(过滤)
        stringCollection.stream()
                .filter((s) -> s.startsWith("a")).forEach(System.out::print); //aaa2 aaa1
        System.out.println("===");
        stringCollection.stream()
                .filter(s -> s.contains("a")).forEach(System.out::print);//aaa2 aaa1
        System.out.println("===");

        //sorted 排序只创建了一个排列好后的Stream, 而不会影响原有的数据源
        stringCollection.stream().sorted()
                .filter(s -> s.startsWith("a")).forEach(System.out::print); //aaa1 aaa2
        System.out.println("===");
        System.out.println(stringCollection);
        //[ddd2, aaa2, bbb1, aaa1, bbb3, ccc, bbb2, ddd1]

        System.out.println("===");
        stringCollection.stream()
                .map(s -> s.toUpperCase()).forEach(System.out::print);
        System.out.println("===");
        stringCollection.stream()
                .map(String::toUpperCase)
                .sorted(String::compareTo)
                .forEach(System.out::print);

        //测试Match操作
        boolean anyStartWithA = stringCollection.stream()
                .anyMatch(s -> s.startsWith("a")); //true
        System.out.println(anyStartWithA);

        stringCollection.stream()
                .allMatch(s -> s.startsWith("a")); //false

        stringCollection.stream()
                .noneMatch(s -> s.startsWith("z"));  //true

        //Count 计数
        long startWithB = stringCollection.stream()
                .filter(s -> s.startsWith("b"))
                .count();
        */

        //reduce
        Optional<String> reduce = stringCollection.stream()
                .reduce((s, s2) -> s + "#" + s2);
        reduce.ifPresent(System.out::println);

        // 字符串连接，concat = "ABCD"
        String concat = Stream.of("A", "B", "C", "D").reduce("", String::concat);

        // 求最小值，minValue = -3.0
        double minValue = Stream.of(-1.5, 1.0, -3.0, -2.0).reduce(Double.MAX_VALUE, Double::min);

        // 求和，sumValue = 10, 有起始值
        int sumValue = Stream.of(1, 2, 3, 4).reduce(0, Integer::sum);
        // 求和，sumValue = 10, 无起始值
        sumValue = Stream.of(1, 2, 3, 4).reduce(Integer::sum).get();

        // 过滤，字符串连接，concat = "ace"
        concat = Stream.of("a", "B", "c", "D", "e", "F")
                .filter(x -> x.compareTo("Z") > 0)
                .reduce("", String::concat);

    }
}
